﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using SharedCongkak;

namespace Congkak
{
    public class SowingState: GameState
    {

        TimeSpan sowInterval = new TimeSpan(5000000);
        TimeSpan currentInterval = new TimeSpan();
        AbstractHole currentHole;
        SeedQueue seedQueue;
        bool isDone;

        public SowingState(GameplayScreen gamePlay, AbstractHole selectedHole, SeedQueue seedQueue)
            : base(gamePlay)
        {
            this.currentHole = selectedHole;
            this.seedQueue = seedQueue;
        }

        private void SowNextHole()
        {
            Seed seed = seedQueue.Pop();
 
            if (currentHole.NextEdges.Count > 0)
            {
                currentHole = currentHole.NextEdges.First().Target;
            }
            
            Sound.Play(SoundEntry.LandMarbles);
            currentHole.AddSeed(seed);
            level.HighlightHole(currentHole, null);
        }

        public override void Update(GameTime gameTime)
        {
            currentInterval += gameTime.ElapsedGameTime;
            if (!isDone)
            {
                if (currentInterval > sowInterval)
                {
                    SowNextHole();
                    if (seedQueue.NoOfSeeds == 0)
                        isDone = true;
                    currentInterval -= sowInterval;
                }
            }
            else
            {
                if (currentHole is Store
                    || currentHole.NoOfSeeds == 1
                    || currentHole.NextEdges.Count == 0)
                {
                    gamePlay.ChangeGameState(new PickState(gamePlay));
                }
                else
                    gamePlay.ChangeGameState(new CollectingState(gamePlay, currentHole, seedQueue));
            }            
        }
    }
}
